package com.yuncheng.spcyApi.spcyService;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yuncheng.spcyApi.busService.BusService;
import com.yuncheng.spcyApi.constant.common.ClientJumpUrlConstant;
import com.yuncheng.spcyApi.constant.common.LogConstant;
import com.yuncheng.spcyApi.constant.common.SpcyCommonConstant;
import com.yuncheng.spcyApi.constant.common.SpcyConstant;
import com.yuncheng.spcyApi.constant.schedule.ScheduleConstant;
import com.yuncheng.spcyApi.constant.wjml.WjmlConstant;
import com.yuncheng.spcyApi.entity.SpcySqsxBasic;
import com.yuncheng.spcyApi.entity.SpcySqsxXpjl;
import com.yuncheng.spcyApi.entity.SpcySqsxYwxx;
import com.yuncheng.entity.YcSysUser;
import com.yuncheng.exception.BusinessException;
import com.yuncheng.spcyApi.schedule.SmsTimerTask;
import com.yuncheng.spcyApi.scheduleJob.ScheduleJobService;
import com.yuncheng.spcyApi.service.*;
import com.yuncheng.spcyApi.utils.GetUuIdUtils;
import com.yuncheng.spcyApi.utils.StringPatternUtils;
import com.yuncheng.spcyApi.vo.common.Result;
import com.yuncheng.spcyApi.vo.jcy.HcyXpVo;
import com.yuncheng.vo.HttpResult;
import com.yuncheng.spcyApi.vo.sqsx.SqsxXpryNumVo;
import com.yuncheng.spcyApi.vo.sqsx.SqsxZzZyYbNumVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import utils.DateConversionUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.Executor;

/**
 * 自动选派-选派人员-定时任务
 * @author hua
 */
@Component(value = "xpryTimedTasksService")
public class XpryTimedTasksService {

    @Resource
    @Lazy
    private BusService busService;

    @Resource
    private ISpcySqsxXpjlService spcySqsxXpjlService;

    @Resource
    private ISpcyLogService spcyLogService;

    @Resource
    private IYcSysUserService ycSysUserService;

    @Resource
    private ISpcySqsxBaiscService spcySqsxBaiscService;

    @Resource
    private ClientJumpUrlConstant clientJumpUrlConstant;

    @Resource
    private ISpcySqsxYwxxService spcySqsxYwxxService;

    @Resource
    private ISpcySqsxXptjjlService spcySqsxXptjjlService;

    @Resource
    @Lazy
    private SmsTimerTask smsTimerTask;

    @Resource
    @Lazy
    private ScheduleJobService scheduleJobService;

    /**
     * 创建自动选派人员-业务
     * @param hcyXpVo
     */
    public void initAutoXpryYwxx(HcyXpVo hcyXpVo){
        if (StringUtils.isBlank(hcyXpVo.getSqsxid())){
            throw new BusinessException("参数为空！");
        }

        SpcySqsxBasic sqsx = busService.getSqsxInfoBySqsxId(hcyXpVo.getSqsxid());
        if (sqsx == null){
            throw new BusinessException("没有相匹配的数据！");
        }

        if (sqsx.getFcykssj() == null || sqsx.getFcyjssj() == null){
            throw new BusinessException("请先选择检查时间并保存！");
        }
        hcyXpVo.setFtzsj(DateUtil.offsetDay(sqsx.getFcykssj(), -1));

        hcyXpVo.setFywflcode(sqsx.getFywflcode());

        SpcySqsxYwxx ywxx = spcySqsxYwxxService.addAutoXpryYwxx(hcyXpVo);

        /** 初始化定时任务 */
        scheduleJobService.initScheduleBySqsxAutoXpry(ywxx);

        /** 取消异步线程 */
        this.timedTasksAutoXpryYwxx(ywxx.getId(), ywxx);
    }

    /**
     * 获取已选派人员的数量及状态-根据检查身份-判断当前是否允许发送短信
     */
    public SqsxXpryNumVo getYxprySlhzt(String sqsxid){
        return busService.getYxprySlhzt(sqsxid);
    }

    /**
     * 获取同意选派人员的数量及状态
     */
    public SqsxXpryNumVo getTyxprySlhzt(String sqsxid, SqsxXpryNumVo oldNumVo){

        // 已经同意选派人员
        SqsxZzZyYbNumVo tyXpNum = spcySqsxXpjlService.getTyXpZzZyYbNumBean(sqsxid);
        oldNumVo.setTyFzzrs(tyXpNum.getFzzrs());
        oldNumVo.setTyFzyrs(tyXpNum.getFzyrs());
        oldNumVo.setTyFybrs(tyXpNum.getFybrs());

        int wcsize = 0;
        if ((oldNumVo.getTyFzzrs() < oldNumVo.getOrgFzzrs())){
            wcsize = 1;
        }
        if ((oldNumVo.getTyFzyrs()< oldNumVo.getOrgFzyrs())){
            wcsize = 1;
        }
        if ((oldNumVo.getTyFybrs() < oldNumVo.getOrgFybrs())){
            wcsize = 1;
        }

        // 同意人数是否满足预设人数
        if (wcsize == 0){
            oldNumVo.setWczt(true);
        }

        // 是否存在人员变动
        List<String> rybgList = spcySqsxXpjlService.getTyXpXpjlListNotSendJctzSms(sqsxid);
        if (CollectionUtil.isNotEmpty(rybgList)){
            oldNumVo.setRybgzt(true);
        }

        return oldNumVo;
    }

    /**
     * 验证当前选派记录-是否能够发送短信(选派人员数量是否已经满足事项)
     */
    public boolean verifySfSendSmsByFssk(SqsxXpryNumVo numVo, String sqsxid, String fssk){
        return busService.verifySfSendSmsByFssk(numVo, sqsxid, fssk);
    }

    /**
     * 获取申请事项-自动选派人员任务列表
     * */
    public List<SpcySqsxYwxx> queryAutoXpryYwxxList(String sqsxid){
        return spcySqsxYwxxService.getAutoXpryYwxxList(sqsxid);
    }

    /**
     * 验证申请事项是否存在执行中自动选派人员任务
     * @return true: 存在
     * */
    public HttpResult verifyAutoXpryYwxxIsExists(String sqsxid){
        boolean flag = spcySqsxYwxxService.verifyAutoXpryYwxxIsExists(sqsxid);

        return HttpResult.ok(flag);
    }

    /**
     * 提前结束-执行中的自动抽选任务列表
     */
    public void tjEndZxzAutoXpryRwList(String sqsxid){
        List<SpcySqsxYwxx> list = spcySqsxYwxxService.getZxzAutoXpryYwxxList(sqsxid);
        if (CollectionUtil.isNotEmpty(list)) {
            for (SpcySqsxYwxx bean : list) {
                scheduleJobService.removeScheduleByMethodParams(bean.getId());
            }
            spcySqsxYwxxService.updateAutoXpryYwxxByState(sqsxid);
        }
    }

    /**
     * 定时任务-自动选派人员
     * @param id
     */
    @Async(value = "asyncSimpleTask")
    public void timedTasksAutoXpryYwxx(String id, SpcySqsxYwxx ywxx){
        if (ywxx == null) {
            ywxx = spcySqsxYwxxService.getById(id);
            if (ywxx == null) {
                return;
            }
        }

        // 结束
        if (ywxx.getFstate() == 1){
            return;
        }

        // 超时移除定时任务
        if (ywxx.getFtzsj() != null){
            int flag = ywxx.getFtzsj().compareTo(new Date());
            if (flag < 0){
                scheduleJobService.removeScheduleByMethodParams(ywxx.getId());

                ywxx.setFstate(SpcyCommonConstant.SQSX_YWXX_STATE_END);
                ywxx.setFjssj(new Date());
                spcySqsxYwxxService.updateById(ywxx);
                return;
            }
        }

        // 定时选派未确认人员
//        List<SpcySqsxXpjl> dsxpIndexWqrList = spcySqsxXpjlService.getDsxpIndexWqrList(ywxx.getId());
        SpcySqsxBasic sqsx = spcySqsxBaiscService.selectSqsxInfoById(ywxx.getSqsxid());

        int fzzrs = 0;
        int fzyrs = 0;
        int fybrs = 0;

        // 获取事项已有选派人数
        SqsxXpryNumVo sqsxNumVo = this.getYxprySlhzt(ywxx.getSqsxid());
        if (!sqsxNumVo.isZzFlag()){
            fzzrs = 0;
        }else {
            fzzrs = (ywxx.getFzzrs() > ywxx.getTyzzrs()) ? ywxx.getFzzrs()-ywxx.getTyzzrs() : 0;
        }

        if (!sqsxNumVo.isZyFlag()){
            fzyrs = 0;
        }else {
            fzyrs = (ywxx.getFzyrs() > ywxx.getTyzyrs()) ? ywxx.getFzyrs()-ywxx.getTyzyrs() : 0;
        }

        if (!sqsxNumVo.isYbFlag()){
            fybrs = 0;
        }else {
            fybrs = (ywxx.getFybrs() > ywxx.getTyybrs()) ? ywxx.getFybrs()-ywxx.getTyybrs() : 0;
        }

//        if (ywxx.getFywflcode().equals(SpcyConstant.YWFL_CODE_YPSC)){

            HcyXpVo hcyXpVo = new HcyXpVo();
            hcyXpVo.setFdsxpywid(ywxx.getId());
            hcyXpVo.setHbqy(ywxx.getHbqy());
            hcyXpVo.setZytc(ywxx.getZytc());
            hcyXpVo.setSqsxid(ywxx.getSqsxid());
            hcyXpVo.setFdqrdxnr(ywxx.getFdqrdxnr());
            hcyXpVo.setFsmszt(ywxx.getFsmszt());
            hcyXpVo.setFzzrs(ywxx.getFzzrs());
            hcyXpVo.setFzyrs(ywxx.getFzyrs());
            hcyXpVo.setFybrs(ywxx.getFybrs());

            /** 初始化选派条件记录 */
            String fxptjid = GetUuIdUtils.ReplaceUuId();
            String xpfs =  SpcyConstant.XPTJ_XPFS_ZDCX;
            spcySqsxXptjjlService.initXptjjl(fxptjid, hcyXpVo.getSqsxid(), xpfs, hcyXpVo, 0, 0, 0, "");

//            boolean xpFlag = true;
            if (fzzrs > 0){
                /*xpFlag = true;
                if (CollectionUtil.isNotEmpty(dsxpIndexWqrList)){
                    int size = dsxpIndexWqrList.stream()
                            .filter(f -> f.getFssk().equals(SpcyConstant.HCY_SSK_ZZ))
                            .collect(Collectors.toList())
                            .size();
                    if (size>0){
                        xpFlag=false;
                    }
                }
                if (xpFlag){
                }*/

                busService.xpHcyByAutoInYpsc(hcyXpVo, ywxx.getSqsxid(), sqsx, SpcyConstant.HCY_SSK_ZZ, SpcyConstant.HCY_USERTYPE_JCY, ywxx.getZytc(), ywxx.getHbqy(), "", ywxx.getFywflcode(), ywxx.getJckssj(), ywxx.getJcjssj(), fzzrs, fzyrs, fybrs, fxptjid, xpfs);
            }

            if (fzyrs > 0){
                /*xpFlag = true;
                if (CollectionUtil.isNotEmpty(dsxpIndexWqrList)){
                    int size = dsxpIndexWqrList.stream()
                            .filter(f -> f.getFssk().equals(SpcyConstant.HCY_SSK_ZY))
                            .collect(Collectors.toList())
                            .size();
                    if (size>0){
                        xpFlag=false;
                    }
                }

                if (xpFlag) {
                }*/

                busService.xpHcyByAutoInYpsc(hcyXpVo, ywxx.getSqsxid(), sqsx, SpcyConstant.HCY_SSK_ZY, SpcyConstant.HCY_USERTYPE_JCY, ywxx.getZytc(), ywxx.getHbqy(), "", ywxx.getFywflcode(), ywxx.getJckssj(), ywxx.getJcjssj(), fzzrs, fzyrs, fybrs, fxptjid, xpfs);

            }

            if (fybrs > 0){
                /*xpFlag = true;
                if (CollectionUtil.isNotEmpty(dsxpIndexWqrList)){
                    int size = dsxpIndexWqrList.stream()
                            .filter(f -> f.getFssk().equals(SpcyConstant.HCY_SSK_YB))
                            .collect(Collectors.toList())
                            .size();
                    if (size>0){
                        xpFlag=false;
                    }
                }

                if (xpFlag) {
                }*/

                busService.xpHcyByAutoInYpsc(hcyXpVo, ywxx.getSqsxid(), sqsx, SpcyConstant.HCY_SSK_YB, SpcyConstant.HCY_USERTYPE_JCY, ywxx.getZytc(), ywxx.getHbqy(), "", ywxx.getFywflcode(), ywxx.getJckssj(), ywxx.getJcjssj(), fzzrs, fzyrs, fybrs, fxptjid, xpfs);
            }

            /** 是否发送待确认短信 */
            this.autoZdxhcxSendDqrSms(hcyXpVo, ywxx, sqsx);



    }

    /**
     * 构建发送选派短信
     * @param xpjl
     * @param sqsx
     * @return
     */
    public String genXprySendSms(SpcySqsxXpjl xpjl, SpcySqsxBasic sqsx, String sqsxid){

        if (sqsx == null){
            sqsx = busService.getSqsxInfoBySqsxId(sqsxid);
        }
        String url = clientJumpUrlConstant.http_url; // 跳转https路径

        /** 发送短信的内容 */
        StringBuffer msg = new StringBuffer();
        String msgType = "";
        msg.append("尊敬的").append(xpjl.getFjcyxm());
        // 查验
        if (StringUtils.isBlank(xpjl.getFspcylx()) || xpjl.getFspcylx().equals(SpcyConstant.FLOW_TYPE_CY)){
            msg.append(SpcyConstant.HCY_USERTYPE_JCY);
            msgType = "检查";
        }else {
            msg.append(SpcyConstant.HCY_USERTYPE_ZJ);
            msgType = "审评";
        }
        msg.append("同志: ").append("\n").append("现有如下");
        if (StringUtils.isBlank(xpjl.getFspcylx()) || xpjl.getFspcylx().equals(SpcyConstant.FLOW_TYPE_CY)){
            msg.append(SpcyConstant.SQSX_SCMS_XCJC);
        }else {
            msg.append(SpcyConstant.SQSX_SCMS_JSSC);
        }
        msg.append("任务").append("。").append("\n");
        msg.append("事项名称").append(": ").append(sqsx.getFsxmc()).append(",").append("\n");
        msg.append("企业名称").append(": ").append(sqsx.getFqymc()).append(",").append("\n");
        if (StringUtils.isNotBlank(sqsx.getFszdq())) {
            msg.append("所在地市").append(": ").append(sqsx.getFszdq()).append(",").append("\n");
        }
        if (StringUtils.isNotBlank(sqsx.getFqyzszcdz())) {
            msg.append("注册地址").append(": ").append(sqsx.getFqyzszcdz()).append(",").append("\n");
        }
        if (StringUtils.isNotBlank(sqsx.getFxxdz())) {
            msg.append("详细地址").append(": ").append(sqsx.getFxxdz()).append(",").append("\n");
        }

        String kssj = ""; // 开始时间
        String jssj = ""; // 结束时间

        // 选派类型- 检查员/专家
        if (StringUtils.isBlank(xpjl.getFspcylx()) || xpjl.getFspcylx().equals(SpcyConstant.FLOW_TYPE_CY)){
            if (sqsx.getFcykssj() != null){
                kssj = DateConversionUtils.DateToYMDString(DateConversionUtils.DateToString(sqsx.getFcykssj()));
            }
            if (sqsx.getFcyjssj() != null){
                jssj = DateConversionUtils.DateToYMDString(DateConversionUtils.DateToString(sqsx.getFcyjssj()));
            }
        }else {
            if (sqsx.getFspkssj() != null){
                kssj = DateConversionUtils.DateToYMDString(DateConversionUtils.DateToString(sqsx.getFspkssj()));
            }
            if (sqsx.getFspjssj() != null){
                jssj = DateConversionUtils.DateToYMDString(DateConversionUtils.DateToString(sqsx.getFspjssj()));
            }
        }
        msg.append(msgType).append("时间为").append(": ").append(kssj).append("至").append(jssj).append("。").append("\n");
        msg.append("请您在").append("3个小时内").append("通过如下链接回复是否同意本次选派，谢谢！").append("\n");

        msg.append("回复链接").append(": ");
        msg.append(url + ClientJumpUrlConstant.sendSmsByXpjlQr_URl_2); // 客户端跳转路径

        msg.append("?").append("id").append("=").append(xpjl.getId()).append("\n");
        msg.append("(主要事项)").append(": ").append("如果在3个小时内未进行回复，本次选派将默认[不同意]。");

        return msg.toString();
    }

    /**
     * 构建-抽选人员-发送待确认选派短信
     * @param xpjl
     * @param sqsx
     * @return
     */
    public String genXprySendSmsNew(SpcySqsxXpjl xpjl, SpcySqsxBasic sqsx, String sqsxid){

        if (sqsx == null){
            sqsx = busService.getSqsxInfoBySqsxId(sqsxid);
        }

        String fzbr = StringPatternUtils.getStringsByIds(sqsx.getFzbr())[0];
        YcSysUser user = ycSysUserService.getById(fzbr);


        /** 检查员您好！我中心随机选派您参与20XX年XX月XX日—XX月XX日
         * 组织的药品XXXXX现场检查（检查地址：XX市），
         * 请您在时限30分钟内（截止时间xx日xx点xx分）回复数字1或2，1.确认参加，2.不参加，谢谢您的大力支持。
         * 联系人： XXX    电话：0771-5886193
         * */
        String msg = "";
        msg += "检查员您好！";
        msg += "\n";

        String kssj = ""; // 开始时间
        String jssj = ""; // 结束时间
        String jzrq = ""; // 截止时间-当前时间30分钟后
        if (xpjl != null) {
            if (xpjl.getFdqrjzsj() != null){
                jzrq = DateConversionUtils.DateToMDHMString(xpjl.getFdqrjzsj());
            }else {
                if (xpjl.getFsmssj() == null) {
                    jzrq = DateConversionUtils.DateToMDHMString(DateUtil.offsetMinute(new Date(), ScheduleConstant.Schedule_Task_Expire_Xpry_Qr_Sms_Cron_Miu));
                } else {
                    jzrq = DateConversionUtils.DateToMDHMString(DateUtil.offsetMinute(xpjl.getFsmssj(), ScheduleConstant.Schedule_Task_Expire_Xpry_Qr_Sms_Cron_Miu));
                }
            }
        }else {
            jzrq = "$jzrq$"; // 替换关键字
        }

        // 检查员
        if (sqsx.getFcykssj() != null){
            kssj = DateConversionUtils.DateToYMDString(DateConversionUtils.DateToString(sqsx.getFcykssj()));
        }
        if (sqsx.getFcyjssj() != null){
            jssj = DateConversionUtils.DateToYMDString(DateConversionUtils.DateToString(sqsx.getFcyjssj()));
        }

        msg += "   我中心随机选派您参与";
        msg += kssj + "至" + jssj;
        msg += "组织的" + sqsx.getFsxmc() + "现场检查";
        msg += "（检查地址：";

        if (StringUtils.isNotBlank(sqsx.getFjcdd())){
            msg += sqsx.getFjcdd();
        }else if (StringUtils.isNotBlank(sqsx.getFszdq())){
            msg += sqsx.getFszdq();
        }else if (StringUtils.isNotBlank(sqsx.getFqyzszcdz())){
            msg += sqsx.getFqyzszcdz();
        }

        msg += "）,";
        msg += "请您在时限30分钟内";
        msg += "（截止时间" + jzrq + "）";
        msg += "回复数字1或2，1.确认参加，2.不参加，谢谢您的大力支持。";
        msg += "\n";

        if (user != null) {
            msg += "   联系人：" + user.getRealname();
        }else {
            msg += "   联系人：" + "李杉";
        }
        msg += "\n";

        if (user != null && StringUtils.isNotBlank(user.getFdwdh())){
            msg += "   联系电话：" + user.getFdwdh();
        }else {
            msg += "   联系电话：" + "0771-5886193";
        }
        /*if (user != null) {
            msg += "   联系人：" + user.getRealname();
            msg += " 联系电话： "+ user.getPhone();
        }*/

        return msg;
    }

    /** 获取检查通知短信 */
    public String genJctzSmsContent(String sqsxid){

        SpcySqsxBasic sqsx = busService.getSqsxInfoBySqsxId(sqsxid);
        if (sqsx == null){
            return "";
        }

        // 同意选派人员列表
        List<SpcySqsxXpjl> tyList = spcySqsxXpjlService.getTyXpXpjlList(sqsxid, null);
        String zzMsg = "";
        String zyMsg = "";
        String ybMsg = "";
        for (int i = 0; i < tyList.size(); i++) {

            if (StringUtils.isNotBlank(tyList.get(i).getFssk())){
                if (tyList.get(i).getFssk().equals(SpcyConstant.HCY_SSK_ZZ)){
                    zzMsg += StringUtils.isBlank(zzMsg) ? "组长：" : "/";
                    zzMsg += tyList.get(i).getFjcyxm();

                }else if (tyList.get(i).getFssk().equals(SpcyConstant.HCY_SSK_ZY)){
                    zyMsg += StringUtils.isBlank(zyMsg) ? "组员：" : "/";
                    zyMsg += tyList.get(i).getFjcyxm();

                }else if (tyList.get(i).getFssk().equals(SpcyConstant.HCY_SSK_YB)){
                    ybMsg += StringUtils.isBlank(ybMsg) ? "预备检查员：" : "/";
                    ybMsg += tyList.get(i).getFjcyxm();

                }
            }
        }

        String fzbr = StringPatternUtils.getStringsByIds(sqsx.getFzbr())[0];
        YcSysUser user = ycSysUserService.getById(fzbr);

        /**
         尊敬的检查员：
               欢迎您参加此次检查工作！我中心选派您参与2024年4月27日至2024年4月28日组织的
         药品生产企业设立审批（许可检查）现场检查（检查地址：梧州）,组长xxxx组员为xxxxx，
         请您在现场检查过程中自觉维护检查工作的公正性和严肃性，
         严格执行自治区药监局药品现场检查人员廉洁自律规范，严格遵守本中心现场检查纪律。
         感谢您对中心工作的支持，祝您工作顺利谢谢您的大力支持。
         联系人：李杉
         联系电话：0771-5886193
         广西壮族自治区食品药品审评查验中心
         */
        String msg = "";
        msg += "尊敬的专家：";
        msg += "\n";

        String kssj = ""; // 开始时间
        String jssj = ""; // 结束时间

        // 检查员
        if (sqsx.getFcykssj() != null){
            kssj = DateConversionUtils.DateToYMDString(DateConversionUtils.DateToString(sqsx.getFcykssj()));
        }
        if (sqsx.getFcyjssj() != null){
            jssj = DateConversionUtils.DateToYMDString(DateConversionUtils.DateToString(sqsx.getFcyjssj()));
        }
        msg += "    ";
        msg += "欢迎您参加此次审评工作！我单位选派您参与";
        msg += kssj + "至" + jssj;
        msg += "组织的" + sqsx.getFsxmc();
        msg += "（" + sqsx.getFjclx() + "）" + "现场评审";
        msg += "（评审地址：";

        /*msg += "   我中心选派您参与";
        msg += kssj + "至" + jssj;
        msg += "组织的" + sqsx.getFsxmc();
        msg += "（" + sqsx.getFjclx() + "）" + "现场检查";
        msg += "（检查地址：";*/

        if (StringUtils.isNotBlank(sqsx.getFjcdd())){
            msg += sqsx.getFjcdd();
        }else if (StringUtils.isNotBlank(sqsx.getFszdq())){
            msg += sqsx.getFszdq();
        }else if (StringUtils.isNotBlank(sqsx.getFqyzszcdz())){
            msg += sqsx.getFqyzszcdz();
        }

        msg += "）,";
        if (StringUtils.isNotBlank(zzMsg)) {
            msg += zzMsg + "，";
        }
        if (StringUtils.isNotBlank(zyMsg)) {
            msg += zyMsg + "，";
        }
        if (StringUtils.isNotBlank(ybMsg)) {
            msg += ybMsg + "，";
        }

        msg += "请您在审评过程中自觉维护审评工作的公正性和严肃性。";
        msg += "\n";
        msg += "    ";
        msg += "感谢您对单位工作的支持，祝您工作顺利谢谢您的大力支持。";
        msg += "\n";

        if (user != null) {
            msg += "    ";
            msg += "联系人：";
            msg += user.getRealname();
        }else {
            msg += "    ";
            msg += "联系人：";
        }

        msg += "\n";

        if (user != null && StringUtils.isNotBlank(user.getFdwdh())){
            msg += "    ";
            msg += "联系电话：单位";
        }else {
            msg += "    ";
            msg += "联系电话：";
        }

        msg += "\n";
//        msg += "广西壮族自治区食品药品审评查验中心";

        return msg;
    }

    /**
     * 自动循环抽选-给选派人员发送待确认短信
     */
    private void autoZdxhcxSendDqrSms(HcyXpVo hcyXpVo, SpcySqsxYwxx ywxx, SpcySqsxBasic sqsx){
        if (StringUtils.isBlank(hcyXpVo.getFsmszt()) || hcyXpVo.getFsmszt().equals(SpcyConstant.XPJL_SMSZT_NO)){
            return;
        }

        String content = "";
        if (StringUtils.isBlank(ywxx.getFdqrdxnr())) {
            content = this.genXprySendSmsNew(null, sqsx, ywxx.getSqsxid());
            ywxx.setFdqrdxnr(content);
        }else {
            content = ywxx.getFdqrdxnr();
        }


        List<SpcySqsxXpjl> xpjlList = spcySqsxXpjlService.list(new LambdaQueryWrapper<SpcySqsxXpjl>()
                .eq(SpcySqsxXpjl::getFdsxpywid, ywxx.getId())
                .eq(SpcySqsxXpjl::getFsmszt, SpcyConstant.XPJL_SMSZT_NO));
        for (int i = 0; i < xpjlList.size(); i++) {

            /** 验证选派人数是否已经满足,不满足发送短信 */
            if (verifySfSendSmsByFssk(null, ywxx.getSqsxid(), xpjlList.get(i).getFssk())) {

                content = this.replaceDqrSmsContentJzsj(content, xpjlList.get(i), sqsx, ywxx.getSqsxid());

                boolean flag = smsTimerTask.smsTimerTaskXpjlServiceNew(xpjlList.get(i), xpjlList.get(i).getId(), content);
                if (flag) {
                    scheduleJobService.initScheduleBySendXprySms(xpjlList.get(i).getId());
                }
            }
        }

    }

    /**
     * 套用待确认短信模板-截止时间替换
     * */
    private String replaceDqrSmsContentJzsj(String content, SpcySqsxXpjl xpjl, SpcySqsxBasic sqsx, String sqsxid){
        if (StringUtils.isNotBlank(content) && content.contains("$jzrq$")) {

            if (xpjl.getFdqrjzsj() != null){
                content = content.replace("$jzrq$", DateConversionUtils.DateToMDHMString(xpjl.getFdqrjzsj()));
            }else {
                Date nowDate = new Date();
                if (xpjl.getFsmssj() != null) {
                    nowDate = xpjl.getFsmssj();
                }
                content = content.replace("$jzrq$", DateConversionUtils.DateToMDHMString(DateUtil.offsetMinute(nowDate, ScheduleConstant.Schedule_Task_Expire_Xpry_Qr_Sms_Cron_Miu)));
            }
        }else {
            content = this.genXprySendSmsNew(xpjl, sqsx, sqsxid);
        }

        return content;
    }

    /**
     *  单个发送确认短信-选派人员
     * */
    public void sendQrSmsSingle(String id, String content){
        SpcySqsxXpjl xpjl = spcySqsxXpjlService.getById(id);
        if (xpjl == null){
            throw new BusinessException("没有相匹配的选派数据！");
        }

        if (StringUtils.isBlank(xpjl.getFjcylxdh())){
            throw new BusinessException(xpjl.getFjcyxm()+"联系电话为空！");
        }

        /** 验证用户是否在岗 */
        boolean isUserZg = ycSysUserService.verifyUserFgzztIsZg(xpjl.getFuserid());
        if (!isUserZg){
            throw new BusinessException(xpjl.getFjcyxm()+"("+xpjl.getFssk()+")已经在其他事项被选派了！");
        }

        /** 验证选派人数是否已经满足 */
        boolean flag = verifySfSendSmsByFssk(null, xpjl.getFsqsxid(), xpjl.getFssk());
        if (!flag){
            throw new BusinessException(xpjl.getFssk() + "人数已经超出事项预设的人数！");
        }

        content = this.replaceDqrSmsContentJzsj(content, xpjl, null, xpjl.getFsqsxid());

        /** 发送短信 */
        boolean smsflag = smsTimerTask.smsTimerTaskXpjlServiceNew(xpjl, xpjl.getId(), content);
        if (smsflag) {
            scheduleJobService.initScheduleBySendXprySms(xpjl.getId());
        }else {
            throw new BusinessException("短信发送失败，检查联系电话是否正确！");
        }
    }

    /**
     * 发生检查短信-同意选派的人员
     */
//    @Async(value = "asyncSimpleTask")
    public void sendJctzSmsByTyxpry(String sqsxid, String content){

        // 查询是否存在没有发送短信的人员
        List<String> rybgList = spcySqsxXpjlService.getTyXpXpjlListNotSendJctzSms(sqsxid);
        if (CollectionUtil.isEmpty(rybgList)){
            return;
        }

        if (StringUtils.isBlank(content)){
            content = this.genJctzSmsContent(sqsxid);
        }

        // 给所有同意的人员发送短信
        List<SpcySqsxXpjl> xpjlList = spcySqsxXpjlService.getTyXpXpjlListNotOrder(sqsxid);
        for (SpcySqsxXpjl bean : xpjlList){
            smsTimerTask.sendSmsInJctz(sqsxid, bean.getId(), bean, content);
        }

        // 将所有不同意的人员并已经发送过短信的时间置空
        spcySqsxXpjlService.updateXpjlInJctzSmsEmpty(sqsxid);
    }

    /**
     * 发送选派人员短信过期确认
     * @param xpjlid
     */
    @Async(value = "asyncSimpleTask")
    public void expireXpryQrSms(String xpjlid){
        if (StringUtils.isBlank(xpjlid)){
            return;
        }

        String sqsxid = spcySqsxXpjlService.getXpjlSqsxidById(xpjlid);
        if (StringUtils.isBlank(sqsxid)){
            return;
        }

        // 验证发送短信回复确认状态
        SpcySqsxXpjl xpjl = spcySqsxXpjlService.getById(xpjlid);
        if (!xpjl.getFsftyxp().equals(SpcyConstant.XPJL_SFTYXP_WQY)){
            return;
        }

        // 短信回复状态
        int xpjlSmsHfzt = this.verifySendSmsInXpjlHfzt(xpjl);
        if (xpjlSmsHfzt == 0 || xpjlSmsHfzt == 3) {

            /*if (StringUtils.isNotBlank(xpjl.getFsmsqrzt()) && xpjl.getFsmsqrzt().equals(SpcyConstant.XPJL_SMSQRZR_YES)) {
                return;
            }*/

            xpjl.setFsftyxp(SpcyConstant.XPJL_SFTYXP_NO);
            xpjl.setFbtyyy(SpcyConstant.XPJL_SFTYXP_YCS_YY);
            xpjl.setFsmsqrzt(SpcyConstant.XPJL_SMSQRZR_YES); // // 短信确认状态
            spcySqsxXpjlService.updateById(xpjl);

//            ycSysUserService.updateUserGzztInZg(xpjl.getFuserid());
        }
    }

    /**
     * 申请事项-修改选派人员信息(修改同意/不同意)
     */
    public void updateXpJcyxxInSfty(SpcySqsxXpjl xpjl){
        if (StringUtils.isBlank(xpjl.getId())){
            throw new BusinessException("参数为空！");
        }

        SpcySqsxXpjl nowXpjl = spcySqsxXpjlService.getById(xpjl.getId());
        if (nowXpjl == null){
            throw new BusinessException("没有想匹配的数据！");
        }

        String logNr = "修改选派：【选派人员】为["+nowXpjl.getFjcyxm()+"];" +
                "【是否同意选派】从["+nowXpjl.getFsftyxp()+"]设置为["+xpjl.getFsftyxp()+"];" +
                "【不同意意见】从["+nowXpjl.getFbtyyy()+"]设置为["+xpjl.getFbtyyy()+"];";

        /*nowXpjl.setFbtyyy(xpjl.getFbtyyy());
        if (StringUtils.isNotBlank(xpjl.getFsftyxp())){
            nowXpjl.setFsftyxp(xpjl.getFsftyxp());
        }
        spcySqsxXpjlService.updateById(nowXpjl);*/

        if (StringUtils.isNotBlank(xpjl.getFsftyxp())){
            String oldFsftyxp = nowXpjl.getFsftyxp(); // 旧的是否同意选派

            nowXpjl.setFbtyyy(xpjl.getFbtyyy());
            nowXpjl.setFsftyxp(xpjl.getFsftyxp());

            if (xpjl.getFsftyxp().equals(SpcyConstant.XPJL_SFTYXP_YES)){

                /** 没发送短信需要验证 */
                if (StringUtils.isBlank(nowXpjl.getFsmszt()) || nowXpjl.getFsmszt().equals(SpcyConstant.XPJL_SMSZT_NO)) {
                    /*// 验证是否在岗
                    boolean isUserZg = ycSysUserService.verifyUserFgzztIsZg(nowXpjl.getFuserid());
                    if (!isUserZg) {
                        throw new BusinessException(nowXpjl.getFjcyxm() + "(" + nowXpjl.getFssk() + ")已经在其他事项被选派了！");
                    }*/

                    /** 验证选派人数是否已经满足 */
                    boolean flag = this.verifySfSendSmsByFssk(null, nowXpjl.getFsqsxid(), nowXpjl.getFssk());
                    if (!flag){
                        throw new BusinessException(nowXpjl.getFssk() + "人数已经超出事项预设的人数！");
                    }
                }else {
                    nowXpjl.setFsmsqrzt(SpcyConstant.XPJL_SMSQRZR_YES);
                }

                spcySqsxXpjlService.updateById(nowXpjl);

                // 同意选派
//                ycSysUserService.updateUserGzztInZxrw(nowXpjl.getFuserid());

                // 验证定时任务选派人员是否满足
                SpcySqsxYwxx ywxx = spcySqsxYwxxService.updateAutoXpryTysl(nowXpjl.getFdsxpywid(), nowXpjl.getFssk());
                if (ywxx != null) {
                    scheduleJobService.removeScheduleByMethodParams(nowXpjl.getFdsxpywid());
                }

                // 定时选派-更新选派人员数量
                /*SpcySqsxYwxx ywxx = spcySqsxYwxxService.updateAutoXpryTysl(nowXpjl.getFdsxpywid(), nowXpjl.getFssk());
                if (ywxx != null){
                    scheduleJobService.removeScheduleByMethodParams(nowXpjl.getFdsxpywid());
                }*/
            }else {

                spcySqsxXpjlService.updateById(nowXpjl);

                /** 是否为同意改为不同意 */
                if (oldFsftyxp.equals(SpcyConstant.XPJL_SFTYXP_YES)){
//                    ycSysUserService.updateUserGzztInZg(nowXpjl.getFuserid());

                    // 删除相关人员的函
                    busService.deleteXgInitScFile(nowXpjl.getId(), "", "");
                    // 删除观察员函
                    busService.deleteXgInitScFile("", nowXpjl.getFsqsxid(), WjmlConstant.xpxcgcydh);
                    // 重新生产观察员函
                    busService.initXpxcgcydh(nowXpjl.getFsqsxid(), WjmlConstant.xpxcgcydh, ""); // 初始化文件记录
                }else {

                    // 已经发送确认短信
                    /*if (StringUtils.isNotBlank(nowXpjl.getFsmszt())
                            && nowXpjl.getFsmszt().equals(SpcyConstant.XPJL_SMSZT_YES)){
                        ycSysUserService.updateUserGzztInZg(nowXpjl.getFuserid());
                    }*/
                }

            }

        }

        spcyLogService.addLogs(LogConstant.LOGS_SQSX_BASIC,logNr,nowXpjl.getFsqsxid(),"修改选派人员信息",SpcyConstant.LOGS_SYS_TYPE_XG);
    }

    /**
     * 申请事项-将选派人员组长变为组员
     * @param id 选派记录id
     * */
    public Result updateXpJcySskByZzToZy(String id){

        SpcySqsxXpjl nowXpjl = spcySqsxXpjlService.getById(id);
        if (nowXpjl == null){
            return Result.error("操作失败，没有想匹配的数据！");
        }

        if (!nowXpjl.getFssk().equals(SpcyConstant.HCY_SSK_ZZ)){
            return Result.error("操作失败，只允许组长变为组员！");
        }

        /** 验证选派人数是否已经满足 */
        boolean flag = this.verifySfSendSmsByFssk(null, nowXpjl.getFsqsxid(), SpcyConstant.HCY_SSK_ZY);
        if (!flag){
            return Result.error("操作失败，当前组员人数已经满足！");
        }
        nowXpjl.setFssk(SpcyConstant.HCY_SSK_ZY);
        spcySqsxXpjlService.updateById(nowXpjl);

        String logNr = "修改选派：【选派人员】为["+nowXpjl.getFjcyxm()+"];";
        logNr += "【检查身份】为[组长]设置为[组员];";
        spcyLogService.addLogs(LogConstant.LOGS_SQSX_BASIC, logNr, nowXpjl.getFsqsxid(),"修改选派人员信息",SpcyConstant.LOGS_SYS_TYPE_XG);

        return Result.ok();
    }

    /**
     * 验证发送短信回复确认状态
     */
    @Async(value = "asyncSimpleTask")
    public void verifySendSmsInXpjlHfzt(String sqsxid){
        if (StringUtils.isBlank(sqsxid)){
            return;
        }

        LambdaQueryWrapper<SpcySqsxXpjl> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SpcySqsxXpjl::getFsqsxid, sqsxid);
        queryWrapper.eq(SpcySqsxXpjl::getFsftyxp, SpcyConstant.XPJL_SFTYXP_WQY);
        queryWrapper.eq(SpcySqsxXpjl::getFsmszt, SpcyConstant.XPJL_SMSZT_YES);
        List<SpcySqsxXpjl> list = spcySqsxXpjlService.list(queryWrapper);
        if (CollectionUtil.isEmpty(list)) {
            return;
        }

        for (SpcySqsxXpjl nowXpjl : list){
            this.verifySendSmsInXpjlHfzt(nowXpjl);
        }

    }

    /** 查询短信回复状态-选派记录
     * @return 0: 没有回复短信相关信息； 1：回复同意; 2: 回复不同意; 3: 回复已过期
     * */
    private int verifySendSmsInXpjlHfzt(SpcySqsxXpjl nowXpjl){

        // 查询回复状态
        int xpjlSmsHfzt = 0;

        // 获取当前时间>过期时间
        Date gqDateTime = DateUtil.offsetMinute(nowXpjl.getFsmssj(), ScheduleConstant.Schedule_Task_Expire_Xpry_Qr_Sms_Cron_Miu);
        if ((new Date().getTime() > gqDateTime.getTime())){
            if (nowXpjl.getFsftyxp().equals(SpcyConstant.XPJL_SFTYXP_WQY)){

                nowXpjl.setFsftyxp(SpcyConstant.XPJL_SFTYXP_NO);
                nowXpjl.setFbtyyy(SpcyConstant.XPJL_SFTYXP_YCS_YY);
                nowXpjl.setFsmsqrzt(SpcyConstant.XPJL_SMSQRZR_YES); // 短信确认状态
                boolean flag = spcySqsxXpjlService.updateById(nowXpjl);// 更新选派状态
                if (flag) {
//                    ycSysUserService.updateUserGzztInZg(nowXpjl.getFuserid());

                    scheduleJobService.removeScheduleByMethodParams(nowXpjl.getId());
                }

                xpjlSmsHfzt = 3;
                return 4;
            }
        }

        // 查询回复状态
        if (xpjlSmsHfzt == 0) {
            xpjlSmsHfzt = smsTimerTask.getXpjlSmsHfzt(nowXpjl.getFjcylxdh(), nowXpjl.getFsmssj());

            if (xpjlSmsHfzt == 1) {
                nowXpjl.setFsftyxp(SpcyConstant.XPJL_SFTYXP_YES);

                // 定时选派-更新选派人员数量
                SpcySqsxYwxx ywxx = spcySqsxYwxxService.updateAutoXpryTysl(nowXpjl.getFdsxpywid(), nowXpjl.getFssk());
                if (ywxx != null) {
                    scheduleJobService.removeScheduleByMethodParams(nowXpjl.getFdsxpywid());
                }
            } else if (xpjlSmsHfzt == 2) {
                nowXpjl.setFsftyxp(SpcyConstant.XPJL_SFTYXP_NO);
                nowXpjl.setFbtyyy("不同意");
            }
        }

        if (xpjlSmsHfzt != 0) {

            nowXpjl.setFsmsqrzt(SpcyConstant.XPJL_SMSQRZR_YES); // 短信确认状态
            boolean flag = spcySqsxXpjlService.updateById(nowXpjl);// 更新选派状态
            if (flag) {
                if (xpjlSmsHfzt == 2 || xpjlSmsHfzt == 3) {
//                    ycSysUserService.updateUserGzztInZg(nowXpjl.getFuserid());
                }

                scheduleJobService.removeScheduleByMethodParams(nowXpjl.getId());
            }
        }

        return xpjlSmsHfzt;
    }

    /**
     * 将选派记录为待确认的全部置为未处理(清空记录)
     */
    public void updateDqrXpjlToWcl(String sqsxid, String bz){
        spcySqsxXpjlService.updateDqrXpjlToWcl(sqsxid, bz);
    }

}
